<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/6/2
 * Time: 下午1:13
 */

namespace backend\controllers;

use common\controllers\BaseControllers;
use common\models\LoginForm;
use common\models\ar\User;
use common\models\ar\UserBrokers;

class LoginController extends BaseControllers
{
    public $layout = 'login';

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'minLength' => 4,
                'maxLength' => 4,
                'transparent' => true,
                'offset' => 5,
                'padding' => 4,
            ],
        ];
    }

    public function actionIndex()
    {
        $clientSN = isset($_COOKIE['login_clientSN']) ? $_COOKIE['login_clientSN'] : '';
        return $this->render('index', ['clientSN' => $clientSN]);
    }

    /**
     * 提交
     */
    public function actionSubmit()
    {
        if (!\Yii::$app->request->isPost && !\Yii::$app->request->isAjax) {
            return false;
        }
        $post = \Yii::$app->request;
        $clientSN = trim($post->post('clientSN', ''));
        $password = trim($post->post('password', ''));
        $captcha = trim($post->post('captcha', ''));
        $model = new LoginForm();
        $model->username = $clientSN;
        $model->password = $password;
        $model->captcha = $captcha;
        $time=date("Y-m-d H:i:s");
        $obj=UserBrokers::findOne(['loginName'=>$clientSN]);
        if (empty($obj))
        {
            $code = 4;
            $msg = "账户不存在，请核实是否输入错误";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        if ($obj['loginPsw']!=$password){
            $code = 3;
            $msg = "当前登录的密码不正确，请核实";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        if ($model->login()) {
            //登录的账户名保存到cookie中
            setcookie("login_clientSN", $clientSN, time() + 7 * 24 * 3600, '/');
            $code = 1;
            $msg = "登录成功";
            // header('Location:/#/real-name-check/index');
            exit(json_encode(['code' => $code, 'msg' => $msg]));
         }
         else {
            $code = 0;
            $msg = '未知错误';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
            $errors = $model->getErrors();
            foreach ($errors as $error) {
                foreach ($error as $v) {
                    $msg = $v;
                }
            }
        }
    }
}
